import { Component, OnInit } from '@angular/core';
import { AlertController, LoadingController, ModalController } from '@ionic/angular';
import { CallService } from '../call.service';
import { SelectDirPage } from '../select-dir/select-dir.page';

@Component({
  selector: 'app-index',
  templateUrl: './index.page.html',
  styleUrls: ['./index.page.scss'],
})
export class IndexPage implements OnInit {
  dirs = [];
  constructor(
    private callService: CallService,
    private modalCtrl: ModalController,
    private alertCtrl: AlertController,
  ) { }

  async ngOnInit() {
    this.dirs = await this.callService.call('indexes', { def: ['/tmp', '/home/ender/se'] });
  }

  async addDir() {
    console.log('dir');
    const modal = await this.modalCtrl.create({
      component: SelectDirPage,
    });

    await modal.present();

    const { data } = await modal.onWillDismiss();
    if (!data || !data.dir) {
      return;
    }

    await this.callService.call('index', { msg: '索引中...' }, data.dir);
    this.dirs = await this.callService.call('indexes', { def: ['/tmp', '/home'], msg: '查询中...' });
  }

  async reindex() {
    await this.callService.call('reindex', { msg: '刷新索引中...' });
  }

  async min() {
    await this.callService.call('min', { msg: '重排索引中...' });
  }

  async delIndex(name: string) {
    const alert = await this.alertCtrl.create({
      header: '是否删除索引？',
      message: `是否删除索引目录: ${name}`,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
        }, {
          text: '确定',
          handler: async () => {
            await this.callService.call('delDir', { msg: '删除中...' }, name);
            await this.ngOnInit();
          }
        }
      ]
    });

    await alert.present();
  }
}
